package top.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.api.Constants.SystemConstants;
import top.api.domain.entity.LoginUserDetails;
import top.api.domain.entity.User;
import top.api.mapper.MenuMapper;
import top.api.mapper.UserMapper;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 根据用户名查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);

        User user = userMapper.selectOne(queryWrapper);

        // 查不到直接抛异常 (将被controller异常捕获GlobalExceptionHandler)
        if (Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }

        // 查询权限信息封装
        //返回用户信息
        if(user.getType().equals(SystemConstants.ADMAIN)){
            List<String> list = menuMapper.selectPermsByUserId(user.getId());
            return new LoginUserDetails(user,list);
        }

        return new LoginUserDetails(user,null);
    }
}
